import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential, load_model
from tensorflow.keras.layers import Dense, LSTM, Dropout
import matplotlib.pyplot as plt

# 读取数据
data = pd.read_csv('temperature_data.csv', parse_dates=['date'], index_col='date')

# 数据标准化
scaler = MinMaxScaler(feature_range=(0, 1))
temperature_scaled = scaler.fit_transform(data['temperature'].values.reshape(-1, 1))

# 创建数据集函数
def create_dataset(data, time_step=1):
    X, y = [], []
    for i in range(len(data) - time_step - 1):
        X.append(data[i:(i + time_step), 0])
        y.append(data[i + time_step, 0])
    return np.array(X), np.array(y)

time_step = 10  # 时间步长
X, y = create_dataset(temperature_scaled, time_step)
X = X.reshape(X.shape[0], X.shape[1], 1)

# 数据分割
train_size = int(len(X) * 0.8)
X_train, X_test = X[:train_size], X[train_size:]
y_train, y_test = y[:train_size], y[train_size:]

# 构建神经网络模型
model = Sequential()
model.add(LSTM(50, return_sequences=True, input_shape=(time_step, 1)))
model.add(LSTM(50, return_sequences=False))
model.add(Dropout(0.2))
model.add(Dense(25))
model.add(Dense(1))

model.compile(optimizer='adam', loss='mean_squared_error')

# 训练模型
history = model.fit(X_train, y_train, batch_size=1, epochs=40, validation_data=(X_test, y_test))

# 保存模型
model.save('temperature_prediction_model.h5')

# 预测 2024年6月4日23点的温度
# 获取最近的时间步长的数据
last_24_hours = data['temperature'].values[-24:]
last_24_hours_scaled = scaler.transform(last_24_hours.reshape(-1, 1))
last_24_hours_scaled = last_24_hours_scaled.reshape(1, 24, 1)

# 加载模型
model = load_model('temperature_prediction_model.h5')

# 进行预测
predicted_temperature_scaled = model.predict(last_24_hours_scaled)
predicted_temperature = scaler.inverse_transform(predicted_temperature_scaled)

print(f"预测的2024年6月4日23点的温度为: {predicted_temperature[0][0]:.2f} °C")
